<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共 {{ total }} 条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <!--
            对于按钮的点击权限(type=2 第二级的权限)
            进行判断，如果这个按钮名字在权限表中存在则允许点击，如果没有则不让点击
           -->
          <el-button :disabled="!checkPermission('EMPLOYEE-ADD')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="">
            <template slot-scope="{row}">
              <img v-imgerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" class="staffPhoto" @click="showQrcode(row.staffPhoto)">
            </template></el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push({path:'employees/detail/'+row.id})">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="total,sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[6, 12, 24, 50]"
            :page-size="page.size"
            @size-change="sizeChange"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <AddEmployees :show-dialog.sync="showDialog" @addEmployee="addEmployee" />
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
      <el-dialog title="头像二维码" :visible="showQrcodeDialog" @close="showQrcodeDialog=false">
        <el-row type="flex" justify="center">
          <canvas ref="codeCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, deleteEmployee } from '@/api/employees'
import { formatDate } from '@/filter'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployees from './components/add-employee'
import AssignRole from './components/assign-role'
import Qrcode from 'qrcode'
export default {
  components: {
    AddEmployees,
    AssignRole
  },
  data() {
    return {
      userId: '',
      list: [],
      page: {
        page: 1,
        size: 6
      },
      total: 0,
      showDialog: false,
      showRoleDialog: false,
      showQrcodeDialog: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async exportExcel() {
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      console.log(rows)
      import ('@/vendor/Export2Excel').then(excel => {
        // console.log(excel)
        // const data = [
        //   ['IU', 22, 'A73星云N87号'],
        //   ['李智恩', 23, 'A73星云N86号'],
        //   ['Jony', 24, 'K73星云N85号']
        // ]
        // 准备一本字典
        const headerDict = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }

        const header = Object.keys(headerDict)
        // console.log(header)
        const data = rows.map(item => {
          const arr = []
          for (const key in headerDict) {
            const newKey = headerDict[key]
            if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
              arr.push(formatDate(item[newKey]))
            } else {
              arr.push(item[newKey])
            }
          }
          return arr
        })
        // console.log(data)
        excel.export_json_to_excel({
          header,
          data
        })
      })
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.total = total
      // console.log(rows)
      // console.log(total)
    },
    async deleteEmployee(id) {
      try {
        await this.$confirm('你确定要删除这个员工数据吗?')
        await deleteEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },
    addEmployee() {
      this.getEmployeeList()
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    sizeChange(newSize) {
      this.page.size = newSize
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue) {
      let res = '未知'
      EmployeeEnum.hireType.find(item => {
        if (item.id === cellValue) {
          res = item.value
        }
      })
      return res
    },
    showQrcode(imgUrl) {
      if (!imgUrl) {
        this.$message.error('此图为默认头像')
        return
      } else {
        this.showQrcodeDialog = true
      }
      // vue 提供了一个方法，如果你修改了一个变量会导致页面渲染
      // 你也希望等待页面渲染完之后执行某些操作，可以使用 this.$nextTick
      // 转换并显示二维码
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.codeCanvas, imgUrl)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto{
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
